package com.hqbzl.chat;

import com.hqbzl.chat.handler.*;
import com.hqbzl.chat.protocol.MessageCodec;

import com.hqbzl.chat.protocol.Serializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ChatServer {
    private static final LoginRequestMessageHandler LOGIN_REQUEST_MESSAGE_HANDLER = new LoginRequestMessageHandler();
    private static final GroupExitMessageHandler GROUP_EXIT_MESSAGE_HANDLER = new GroupExitMessageHandler();
    private static final GroupJoinMessageHandler GROUP_JOIN_MESSAGE_HANDLER = new GroupJoinMessageHandler();
    private static final GroupMemberMessageHandler GROUP_MEMBER_MESSAGE_HANDLER = new GroupMemberMessageHandler();
    private static final GroupCreateMessageHandler GROUP_CREATE_MESSAGE_HANDLER = new GroupCreateMessageHandler();
    private static final GrupSendMessageHandler GRUP_SEND_MESSAGE_HANDLER = new GrupSendMessageHandler();
    private static final SendMessageHandler SEND_MESSAGE_HANDLER = new SendMessageHandler();
    public static final LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
    public static final QuitHandler QUIT_HANDLER = new QuitHandler();
    public static final PingRequestHandler PING_REQUEST_HANDLER = new PingRequestHandler();
    public static final MessageCodec MESSAGE_CODEC = new MessageCodec();
    // public static final MessageCodec MESSAGE_CODEC = new MessageCodec();

    public static void main(String[] args) {
        final NioEventLoopGroup boss = new NioEventLoopGroup();
        final NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            final ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.group(boss, worker);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel sc) throws Exception {
                    // 5 秒内如果没有收到数据，会触发 IdleState#READER_IDLE 事件
                    sc.pipeline().addLast(new IdleStateHandler(5, 0, 0));
                    // 即可以同时作为入栈和出栈处理器
                    sc.pipeline().addLast(new ChannelDuplexHandler() {
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            IdleStateEvent event = (IdleStateEvent) evt;
                            if (event.state() == IdleState.READER_IDLE) {
                                log.debug("已经5秒没能读到数据了");
                            }
                            /*
                            else if(event.state() == IdleState.WRITER_IDLE){
                                log.debug("已经5秒没能读到数据了");
                            }
                            */
                            //super.userEventTriggered(ctx, evt);
                        }
                    });
                    sc.pipeline().addLast(LOGGING_HANDLER);
                    sc.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 12, 4, 0, 0));
                    // 必须和粘包半包处理器 LengthFieldBasedFrameDecoder 一起使用，砍保接到的数据是完整的
                    sc.pipeline().addLast(MESSAGE_CODEC);
                    sc.pipeline().addLast(LOGIN_REQUEST_MESSAGE_HANDLER);
                    sc.pipeline().addLast(SEND_MESSAGE_HANDLER);
                    sc.pipeline().addLast(GRUP_SEND_MESSAGE_HANDLER);
                    sc.pipeline().addLast(GROUP_CREATE_MESSAGE_HANDLER);
                    sc.pipeline().addLast(GROUP_MEMBER_MESSAGE_HANDLER);
                    sc.pipeline().addLast(GROUP_JOIN_MESSAGE_HANDLER);
                    sc.pipeline().addLast(GROUP_EXIT_MESSAGE_HANDLER);
                    sc.pipeline().addLast(QUIT_HANDLER);
                    sc.pipeline().addLast(PING_REQUEST_HANDLER);
                }
            });
            final ChannelFuture channelFuture = serverBootstrap.bind(7788).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
